"""
@Author    : ghenyar
@Time      : 2025/8/28 12:30
@File      : log
@Desc      :  日志处理类
"""
import logging
import os
from datetime import datetime
from typing import Dict
from concurrent_log_handler import ConcurrentRotatingFileHandler


class FixedNameFormatter(logging.Formatter):
    def __init__(self, base_name, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.base_name = base_name

    def format(self, record):
        record.name = self.base_name
        return super().format(record)


class LoggingUtil:
    def __init__(self, base_name: str, max_size_mb: int = 10, backup_count: int = 300, ):
        self.base_name = base_name
        self.max_size_mb = max_size_mb
        self.backup_count = backup_count
        self.loggers: Dict[str, logging.Logger] = {}

    def _get_logger(self):
        date = datetime.now().strftime("%Y-%m-%d")
        logger_key = f"{date}"
        file_path = os.path.join("logs", f"{date}.log")
        os.makedirs(os.path.dirname(file_path), exist_ok=True)

        if logger_key not in self.loggers:
            logger = logging.getLogger(f"{self.base_name}.{date}")
            logger.setLevel(logging.INFO)
            logger.propagate = False
            handler = ConcurrentRotatingFileHandler(
                file_path,
                maxBytes=self.max_size_mb * 1024 * 1024,
                backupCount=self.backup_count,
                encoding='utf-8'
            )
            fmt = "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
            formatter = FixedNameFormatter(self.base_name, fmt, datefmt='%Y-%m-%d %H:%M:%S,%f'[:-3])
            handler.setFormatter(formatter)
            logger.addHandler(handler)
            self.loggers[logger_key] = logger
        return self.loggers[logger_key]

    def debug(self, message: str):
        self._get_logger().debug(message)

    def info(self, message: str):
        self._get_logger().info(message)

    def warning(self, message: str):
        self._get_logger().warning(message)

    def error(self, message: str):
        self._get_logger().error(message)

    def critical(self, message: str):
        self._get_logger().critical(message)
